﻿using Ewell.Interface.Common.Model.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ewell.Interface.Common.Utils
{
    public static class ZipFileHelper
    {
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="zipFilePath">压缩到路径</param>
        public static void CompressFile(string filePath, string zipFilePath)
        {
            try
            {
                using (FileStream fileStream = new FileStream(zipFilePath, FileMode.Create))
                {
                    using (ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Create))
                    {
                        string entryName = Path.GetFileName(filePath);
                        archive.CreateEntryFromFile(filePath, entryName);
                    }
                }
            }
            catch (Exception ex)
            {
                new SpeedException("压缩文件失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="extractPath">解压到路径</param>
        public static void UnzipFile(string zipFilePath, string extractPath)
        {
            try
            {
                if (!File.Exists(zipFilePath))
                {
                    throw new FileNotFoundException("不存在当前需要解压的文件!");
                }

                if (!Directory.Exists(extractPath))
                {
                    Directory.CreateDirectory(extractPath);
                }
                 
                using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string extractFullPath = Path.Combine(extractPath, entry.FullName);

                        if (string.IsNullOrEmpty(entry.Name))
                        {
                            Directory.CreateDirectory(extractFullPath);
                        }
                        else
                        {
                            entry.ExtractToFile(extractFullPath, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SpeedException("解压文件失败: " + ex.Message);
            }
        }

    }
}
